import waterMeshTool from '../lib/waterMeshTool'

export default {
    data() {
        return {
            showPayer: false,
            timeList: [],
            colorListYMGC: ['#CE1F1F', '#F0810B', '#F0C90B', '#00A2FB'],
            planID: '',
            cellFile: '',
            curveFile: '',
            nodeFile: '',
            baseWaterColor: 'rgba(36, 69, 81, 0.8)',
            waterArrow1: require('@/assets/map/arrow.png'),
            waterArrow2: require('@/assets/map/arrow.png'),
            waterNormals: require('@/assets/map/waterNormals.jpg'),
            loadingTxt: [],
            loadingTxtStep: '',
            cameraPos: {
                WDC2100129000001: [114.591809, 24.484856, 15000.0], // 大席水
                WDC2100129000006: [114.188117, 24.30656433, 15000.0], // 龙仙水
            }
        }
    },

    beforeDestroy() {
        this.$store.dispatch('playerClose')
        this.clearInWaterMesh()
        this.clearOutWaterMesh()
        this.clearMemory()
        this.$store.getters.eventCesiumOption.leftPickFns.delete('WaterMesh')
    },
    computed: {
        // 流域编码
        basin() {
            return this.$store.getters.basin
        },
        playerIndex() {
            return this.$store.getters.playerIndex
        }
    },
    watch: {
        // playerIndex: {
        //     handler: function(index) {
        //         this.$nextTick(() => {
        //             this.playWaterMesh(index)
        //         })
        //     }
        // },
        loadingTxt: {
            handler: function(val) {
                this.$store.dispatch('mapLoadingText', this.loadingTxt)
            }
        },
        loadingTxtStep: {
            handler: function(val) {
                this.$store.dispatch('mapLoadingTextStep', this.loadingTxtStep)
            }
        }
    },
    created() {
        // var colors05 = waterMeshTool.gradient('#00A2FB', '#F0C90B', 20)
        // var colors51 = waterMeshTool.gradient('#F0C90B', '#F0810B', 20)
        // var colors12 = waterMeshTool.gradient('#F0810B', '#CE1F1F', 20)
        // var colorAll2 = [...colors05, ...colors51, ...colors12]
        // var colorAll3 = ['#00A2FB', '#F0C90B', '#F0810B', '#CE1F1F']
        // var rgbs = []
        // colorAll3.forEach(hex => {
        //     var rgb = []
        //     for (var i = 1; i < 7; i += 2) {
        //         rgb.push(parseInt('0x' + hex.slice(i, i + 2)))
        //     }
        //     rgb[0] = Math.floor(rgb[0] * 10000 / 256) / 10000
        //     rgb[1] = Math.floor(rgb[1] * 10000 / 256) / 10000
        //     rgb[2] = Math.floor(rgb[2] * 10000 / 256) / 10000
        //     rgbs.push(rgb)
        // })
        // console.log(rgbs)
        // this.colorAll = waterMeshTool.gradient('#780000', '#ff0000', 60)
        // var deeps05 = waterMeshTool.gradient('#C2D6FF', '#7A99FF', 20)
        // var deeps51 = waterMeshTool.gradient('#7A99FF', '#518FF5', 20)
        // var deeps12 = waterMeshTool.gradient('#518FF5', '#3371D6', 20)
        // this.deepAll = [...deeps05, ...deeps51, ...deeps12]
        this.lonlats = []
        this.appearance = this.getAppearance('')
        this.appearanceIn = this.getAppearanceIn('')
        //
    },
    mounted() {
        this.$nextTick(() => {
            var cam = this.cameraPos[this.basin]
            this.$viewer.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(cam[0], cam[1], cam[2]),
                orientation: {
                    heading: Cesium.Math.toRadians(0), // east, default value is 0.0 (north)
                    pitch: Cesium.Math.toRadians(-90), // default value (looking down)
                    roll: 0.0 // default value
                },
                duration: 2
            })
            this.initWaterMeshEvent()
            // var obj = {
            //     'id': 'a008aa1e-b973-4e22-b819-94402114b7b4',
            //     'name': '伊洛河100年一遇',
            //     'createDDate': '2023-01-12T19:15:57',
            //     'calculationState': 2,
            //     'rehearsalType': '极端情景',
            //     'hiddendangertype': null,
            //     'predictionStart': '01/12/2023 19:00:00',
            //     'predictionEnd': '01/13/2023 19:00:00',
            //     'measuredstart': '2023-01-11T19:00:00',
            //     'measuredfend': '2023-01-12T19:00:00',
            //     'calculationfile': null,
            //     'cellResult': '\\FileDirectory\\a008aa1e-b973-4e22-b819-94402114b7b4\\CellResult.txt',
            //     'curveResult': '\\FileDirectory\\a008aa1e-b973-4e22-b819-94402114b7b4\\CurveResult.txt',
            //     'nodeResult': '\\FileDirectory\\a008aa1e-b973-4e22-b819-94402114b7b4\\NodeResult.txt'
            // }
            // this.planID = obj.id
            // this.cellFile = obj.cellResult
            // this.curveFile = obj.curveResult
            // this.nodeFile = obj.nodeResult
            // console.time('ssss')
            // this.getAllDatas(false).then(timeList => {
            //     console.log(timeList)
            //     console.timeEnd('ssss')
            //     this.timeList = timeList
            //     var player = this.$store.getters.playerParams
            //     player.name = 'PlanYMGC'
            //     player.dragReal = false
            //     player.width = '50%'
            //     player.show = true
            //     player.currIndex = 0
            //     player.times = timeList
            //     this.$store.dispatch('playerParams', player)
            //     this.playWaterMesh(0)
            // })
        })
    },
    methods: {
        getAppearanceIn(add) {
            var str = ''

            var speed = 0.002
            if (this.hongWater) {
                this.baseWaterColor = 'rgba(135,122,104,0.93)'
            } else {
                this.baseWaterColor = 'rgba(17,113,176,0.9)'
            }
            var appearance = new Cesium.EllipsoidSurfaceAppearance({
                aboveGround: true,
                // uniforms: {
                //     addAlpha: 0.6,
                //     addHeat: false
                // },
                material: new Cesium.Material({
                    fabric: {
                        materials: {
                            waterMaterial: {
                                type: 'Water',
                                uniforms: {
                                    baseWaterColor: new Cesium.Color.fromCssColorString(
                                        this.baseWaterColor
                                    ),
                                    blendColor: new Cesium.Color.fromCssColorString(
                                        this.baseWaterColor
                                    ),
                                    normalMap: this.waterNormals,
                                    specularMap: this.waterNormals,
                                    frequency: 100000.0, // 频率：控制波数的数字。
                                    franimationSpeed: speed * 20,
                                    flowSpeed: speed / 20,
                                    famplitude: 22, // 振幅：控制水波振幅的数字。
                                    specularIntensity: 2
                                },
                                source: `
							uniform sampler2D specularMap;
                            uniform sampler2D normalMap;
                            uniform vec4 baseWaterColor;
                            uniform vec4 blendColor;
                            uniform float frequency;
                            uniform float franimationSpeed;
                            uniform float famplitude;
                            uniform float specularIntensity;
                            czm_material czm_getMaterial(czm_materialInput materialInput)
                            {
                                
                            czm_material material = czm_getDefaultMaterial(materialInput);
                            materialInput.st = 	vec2(fract(materialInput.st.s - czm_frameNumber * flowSpeed), materialInput.st.t);
                            float fade = max(0.9, (length(materialInput.positionToEyeEC) / 10000000000.0) * frequency );
                            float specularMapValue = texture2D(specularMap, materialInput.st).r *0.2 + 0.5;
                            // float specularMapValue =  0.5;
                            vec4 noise = czm_getWaterNoise(normalMap, materialInput.st * frequency, 
                                                            czm_frameNumber * franimationSpeed, 0.0);
                            vec3 normalTangentSpace = noise.xyz * vec3(3.0, 1.0, (1.0 / famplitude));
                            normalTangentSpace.xy /= fade;
                            normalTangentSpace = mix(vec3(0.6, 0.3, 0.2), normalTangentSpace, specularMapValue );
                            normalTangentSpace = normalize(normalTangentSpace);
                            float tsPerturbationRatio = clamp(dot(normalTangentSpace, vec3(0.1, 0.1, 1.0)), 0.1, 1.0);
                            material.alpha = specularMapValue  * 0.5 + 0.5;
                            material.diffuse = mix(blendColor.rgb, baseWaterColor.rgb, specularMapValue);
                            material.diffuse += (0.1 * tsPerturbationRatio);
                            material.diffuse = material.diffuse;
                            material.normal = normalize(materialInput.tangentToEyeMatrix * normalTangentSpace);
                            material.specular = specularIntensity * specularMapValue * noise.z ;
                            // material.shininess =   10.;
                            return material;
                            }`
                            }
                        },
                        components: {
                            diffuse:
                                'waterMaterial.diffuse',
                            alpha: 'waterMaterial.alpha',
                            normal: 'waterMaterial.normal',
                            specular: 'waterMaterial.specular'
                        }
                    },
                    faceForward: true,
                    translucent: true //

                }),
                vertexShaderSource: `
                    attribute vec3 position3DHigh;
                    attribute vec3 position3DLow;
                    attribute vec2 st;
                    attribute float batchId;
                    attribute vec4 color;
                     
                    varying vec4 v_color;
                    varying vec3 v_positionMC;
                    varying vec3 v_positionEC;
                    varying vec2 v_st;
                    void main()
                    {
                        v_color=color;
                        vec4 p = czm_computePosition();
                        v_positionMC = position3DHigh + position3DLow;
                        v_positionEC = (czm_modelViewRelativeToEye * p).xyz;
                        v_st = st;
                        gl_Position = czm_modelViewProjectionRelativeToEye * p;
                    }
                    `,

                fragmentShaderSource: `
                    varying vec3 v_positionMC; 
                    varying vec3 v_positionEC; 
                    varying vec2 v_st; 
                    varying vec4 v_color;
                    
                    void main() 
                    { 
                        czm_materialInput materialInput; 
                        vec3 normalEC = normalize(czm_normal3D * czm_geodeticSurfaceNormal(v_positionMC, vec3(0.0), vec3(1.0))); 
                
                        materialInput.s = v_st.s; 
                        materialInput.st = v_st; 
                        materialInput.str = vec3(v_st, 0.0); 
                        materialInput.normalEC = normalEC; 
                        materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(v_positionMC, materialInput.normalEC); 
                        vec3 positionToEyeEC = -v_positionEC; 
                        materialInput.positionToEyeEC = positionToEyeEC; 
                        czm_material material = czm_getMaterial(materialInput); 
                        // #ifdef FLAT 
                        // gl_FragColor = vec4(material.diffuse + material.emission, material.alpha); 
                        // #else 
                        gl_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC); 
                    } 
                    `,
                faceForward: true
            })
            return appearance
        },
        getAppearance(add) {
            var str = ''
            if (this.addAlpha) {
                str += `
                gl_FragColor.a = v_color.a; 
                `
            }
            if (this.addHeat) {
                str += `
                    float index = v_color.r * 60.; // 取1-60的颜色分段
                    vec3 colorHeat = getColorHeat(index);
                    gl_FragColor.rgb = gl_FragColor.rgb * 0.3 + colorHeat * 0.8;
                    `
            }
            if (this.hongWater) {
                this.baseWaterColor = 'rgba(135,122,104,0.93)'
            } else {
                this.baseWaterColor = 'rgba(17,113,176,0.9)'
            }

            var speed = 0.002
            var appearance = new Cesium.EllipsoidSurfaceAppearance({
                aboveGround: true,
                // uniforms: {
                //     addAlpha: 0.6,
                //     addHeat: false
                // },
                material: new Cesium.Material({
                    fabric: {
                        materials: {
                            waterMaterial: {
                                type: 'Water',
                                uniforms: {
                                    baseWaterColor: new Cesium.Color.fromCssColorString(
                                        this.baseWaterColor
                                    ),
                                    blendColor: new Cesium.Color.fromCssColorString(
                                        this.baseWaterColor
                                    ),
                                    normalMap: this.waterNormals,
                                    specularMap: this.waterNormals,
                                    frequency: 100000.0, // 频率：控制波数的数字。
                                    franimationSpeed: speed * 20,
                                    flowSpeed: speed / 20,
                                    famplitude: 22, // 振幅：控制水波振幅的数字。
                                    specularIntensity: 2
                                },
                                source: `
							uniform sampler2D specularMap;
                            uniform sampler2D normalMap;
                            uniform vec4 baseWaterColor;
                            uniform vec4 blendColor;
                            uniform float frequency;
                            uniform float franimationSpeed;
                            uniform float famplitude;
                            uniform float specularIntensity;
                            czm_material czm_getMaterial(czm_materialInput materialInput)
                            {
                                
                            czm_material material = czm_getDefaultMaterial(materialInput);
                            // materialInput.st = 	vec2(fract(materialInput.st.s - czm_frameNumber * flowSpeed), materialInput.st.t);
                            float fade = max(0.9, (length(materialInput.positionToEyeEC) / 10000000000.0) * frequency );
                            float specularMapValue = texture2D(specularMap, materialInput.st).r *0.2 + 0.5;
                            // float specularMapValue =  0.5;
                            vec4 noise = czm_getWaterNoise(normalMap, materialInput.st * frequency, 
                                                            czm_frameNumber * franimationSpeed, 0.0);
                            vec3 normalTangentSpace = noise.xyz * vec3(3.0, 1.0, (1.0 / famplitude));
                            normalTangentSpace.xy /= fade;
                            normalTangentSpace = mix(vec3(0.6, 0.3, 0.2), normalTangentSpace, specularMapValue );
                            normalTangentSpace = normalize(normalTangentSpace);
                            float tsPerturbationRatio = clamp(dot(normalTangentSpace, vec3(0.1, 0.1, 1.0)), 0.1, 1.0);
                            material.alpha = specularMapValue  * 0.5 + 0.5;
                            material.diffuse = mix(blendColor.rgb, baseWaterColor.rgb, specularMapValue);
                            material.diffuse += (0.1 * tsPerturbationRatio);
                            material.diffuse = material.diffuse;
                            material.normal = normalize(materialInput.tangentToEyeMatrix * normalTangentSpace);
                            material.specular = specularIntensity * specularMapValue * noise.z ;
                            // material.shininess =   10.;
                            return material;
                            }`
                            }
                        },
                        components: {
                            diffuse:
                                ' waterMaterial.diffuse * 1.',
                            alpha: 'waterMaterial.alpha',
                            normal: 'waterMaterial.normal',
                            specular: 'waterMaterial.specular'
                        }
                    },
                    faceForward: true,
                    translucent: true //

                }),
                vertexShaderSource: `
                    attribute vec3 position3DHigh;
                    attribute vec3 position3DLow;
                    attribute vec2 st;
                    attribute float batchId;
                    attribute vec4 color;
                     
                    varying vec4 v_color;
                    varying vec3 v_positionMC;
                    varying vec3 v_positionEC;
                    varying vec2 v_st;
                    void main()
                    {
                        v_color=color;
                        vec4 p = czm_computePosition();
                        v_positionMC = position3DHigh + position3DLow;
                        v_positionEC = (czm_modelViewRelativeToEye * p).xyz;
                        v_st = st;
                        gl_Position = czm_modelViewProjectionRelativeToEye * p;
                    }
                    `,

                fragmentShaderSource: `
                    varying vec3 v_positionMC; 
                    varying vec3 v_positionEC; 
                    varying vec2 v_st; 
                    varying vec4 v_color;
                    

// (3) [0, 0.6328, 0.9804]
// (3) [0.9375, 0.7851, 0.0429]
// (3) [0.9375, 0.5039, 0.0429]
// (3) [0.8046, 0.121, 0.121]
                    vec3 getColorHeat(float index){
                        float rrr = 0.;
                        float ggg = 0.;
                        float bbb = 0.;
                        if(index >= 0. && index < 20.){
                            rrr = index * (1.0 / 20.);
                            ggg = 0.6328 + index * ((0.7851 - 0.6328) / 20.);
                            bbb = 1.- index *  (1.0 / 20.);
                        } else if(index >= 20. && index < 40.){
                            rrr = 0.94;
                            ggg = 0.7851 - (index - 19.) * ((0.7851 - 0.5039) / 20.);
                            bbb = 0.05;
                        }else if(index >= 40.){
                            rrr = 0.94;
                            ggg = 0.5 - (index - 39.) * 0.02;
                            bbb = 0.05;
                        }
    
                        vec3 colorHeat = vec3(rrr, ggg, bbb);
                        return colorHeat;
                    }
                    
                    void main() 
                    { 
                        czm_materialInput materialInput; 
                        vec3 normalEC = normalize(czm_normal3D * czm_geodeticSurfaceNormal(v_positionMC, vec3(0.0), vec3(1.0))); 
                
                        float xx = v_color.y ;
                        float yy = v_color.z ;
                        float time = czm_frameNumber * 0.001;
vec2 nst = vec2(fract(v_st.x  - time * (xx-0.5)),fract(v_st.y - time * (yy-0.5))) ;
materialInput.st =  nst ;
                        materialInput.normalEC = normalEC; 
                        materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(v_positionMC, materialInput.normalEC); 
                        vec3 positionToEyeEC = -v_positionEC; 
                        materialInput.positionToEyeEC = positionToEyeEC; 
                        czm_material material = czm_getMaterial(materialInput); 
                        // #ifdef FLAT 
                        // gl_FragColor = vec4(material.diffuse + material.emission, material.alpha); 
                        // #else 
                        gl_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC); 
                        ` + str +
                    `
                        } 
                    `,
                faceForward: true
            })
            return appearance
        },

        loadTxtReplace(str1, str2) {
            var find = this.loadingTxt.findIndex(item => {
                return item === str1
            })
            this.loadingTxt.splice(find, find + 1, str2)
        },
        txtCell2TimeArr(txt) {
            var rows = txt.split('\r\n')
            rows.pop()
            var time = ''
            var times = []
            var oneTime = []
            rows.forEach(item => {
                if (item[4] === '-') { // 时间行
                    if (oneTime.length > 0) times.push({ time: time, timeData: oneTime })
                    time = item
                    oneTime = []
                    return
                }
                var rowNumber = item.split(' ')
                var meshIndex = Number(rowNumber[0])
                var sw = Number(rowNumber[1])
                var ss = Number(rowNumber[2])
                var a = Number(rowNumber[3])
                if (meshIndex && sw && ss) {
                    oneTime.push([meshIndex, sw, ss, a])
                } else {
                    console.log('网格信息错误', rowNumber)
                    return false
                }
            })
            times.push({ time: time, timeData: oneTime })
            return times
        },
        txtCurve2TimeMap(txt) {
            var rows = txt.data.split('\r\n')
            rows.pop()
            var time = ''
            var times = []
            var oneTime = new Map()
            rows.forEach(item => {
                if (item[4] === '-') { // 时间行
                    if (oneTime.size > 0) times.push({ time: time, timeData: oneTime })
                    time = item
                    oneTime = new Map()
                    return
                }
                var rowNumber = item.split(' ')
                var index = Number(rowNumber[0])
                var sw = Number(rowNumber[1])
                if (index && sw) {
                    // oneTime.push(item)
                    oneTime.set(index, sw)
                } else {
                    console.log('横截面信息错误', rowNumber)
                    return
                }
            })
            times.push({ time: time, timeData: oneTime })
            return times
        },
        txtNode2TimeMap(txt) {
            console.log(txt)
            var rows = txt.data.split('\r\n')
            rows.pop()

            var time = ''
            var times = []
            var oneTime = new Map()
            rows.forEach(item => {
                if (item[4] === '-') { // 时间行
                    if (oneTime.size > 0) times.push({ time: time, timeData: oneTime })
                    time = item
                    oneTime = new Map()
                    return
                }

                var rowNumber = item.split(' ')
                var pointIndex = Number(rowNumber[0])
                var pointH = Number(rowNumber[1])
                if (pointH) {
                    oneTime.set(pointIndex, pointH)
                } else {
                    console.log('点高信息错误', rowNumber)
                    return
                }
            })
            times.push({ time: time, timeData: oneTime })
            return times
        },

        /* 获取方案的所有时间，没有的话就整理入库
        * refresh bool 真为强制重读，不走缓存
        * */
        async getAllDatas(refresh = false, refreshPM = false) {
            this.loadingTxt = []
            return new Promise(async(resolve, reject) => {
                if (!refresh) {
                    this.loadingTxt.push('请求数据中，请稍后...')
                    var getTimesByDB = this.$iDB.getItem(this.planID + '_timeList')
                    var getMeshInByDB = this.$iDB.getItem(this.planID + '_meshIn')
                    var getMeshOutByDB = this.$iDB.getItem(this.planID + '_meshOut')
                    Promise.all([getTimesByDB, getMeshInByDB, getMeshOutByDB]).then(async res => {
                        if (res[0] && res[1] && res[2]) {
                            this.timeList = res[0]
                            this.resArrMeshIn = res[1]
                            this.resArrMeshOut = res[2]
                            resolve(res[0])
                            this.loadingTxt.splice(0, this.loadingTxt.length)
                        } else {
                            this.loadingTxt.splice(0, this.loadingTxt.length)
                            this.reLoadData()
                            return
                        }
                    })
                    return
                }
                this.loadingTxtStep = '请求几何数据中，请稍后...|10%'
                var getPoint = waterMeshTool.getPoints(this.basin, refreshPM)
                var getMesh = waterMeshTool.getMeshs(this.basin, refreshPM)
                const [resPoint, resMesh] = await Promise.all([getPoint, getMesh])
                const maxLon = resPoint.maxLon
                const minLon = resPoint.minLon
                const maxLat = resPoint.maxLat
                const minLat = resPoint.minLat
                if (isNaN(maxLon) || isNaN(minLon) || isNaN(maxLat) || isNaN(minLat)) {
                    console.log('没有点表坐标的最大最小值')
                    this.reLoadData()
                }
                this.loadingTxtStep = '请求节点数据中，请稍后...|25%'

                var resNode
                var timesNodes
                try {
                    resNode = await this.$axios.get(this.nodeFile)
                    this.loadingTxtStep = '整理节点数据中，请稍后...|40%'
                    timesNodes = this.txtNode2TimeMap(resNode)
                    console.log(timesNodes)
                } catch (e) {
                    this.loadingTxtStep = '此方案无淹没区域。|100%'
                    console.log(e)
                    // reject(e)
                    timesNodes = []
                    setTimeout(() => {
                        this.loadingTxtStep = ''
                    }, 2000)
                    return
                }

                this.loadingTxtStep = '请求一维数据中，请稍后...|50%'
                // ------------------------河内----------------------
                this.$axios.get(`/mapData/guangdong/txt/${this.basin}/riverMesh.txt`).then(resMesh => {
                    var mesh = []
                    var meshs = resMesh.data.split('\r\n')
                    meshs.pop() // 去掉最后一行空白，省的每行判断
                    meshs.forEach(item => {
                        var oneRow = item.split('"')
                        var nameLv = oneRow[0].split(',')
                        var curveName = nameLv[0]
                        var a = Math.floor(Number(nameLv[1]) * 1000) / 1000
                        var pointIndexs = []
                        if (curveName && oneRow[1]) {
                            pointIndexs = oneRow[1].split(',')
                            mesh.push([curveName, a, pointIndexs])
                        } else {
                            console.log('河内网格信息错误', oneRow)
                        }
                    })
                    this.loadingTxtStep = '请求淹没数据中，请稍后...|60%'
                    this.$axios.get(this.curveFile).then(resCurve => {
                        var resRows = resCurve.data.split('\r\n')
                        if (resRows.length < 100) {
                            reject('请求一维结果 失败！！！')
                            return false
                        }

                        var worker = new Worker('/worker/meshIn.js')
                        worker.postMessage({
                            resRiverMeshs: mesh,
                            resCurve: resCurve.data,
                            resPoint,
                            timesNodes,
                            hDiff: 0
                        })
                        worker.onmessage = res => {
                            console.log(res)
                            this.$iDB.setItem(this.planID + '_meshIn', res.data)
                            this.resArrMeshIn = res.data
                        }
                    }, e => {
                        this.resArrMeshIn = []
                    })
                })
                // ------------------------河外----------------------
                this.$axios.get(this.cellFile).then(resCell => {
                    if (!(resCell && resCell.data && resCell.data.length > 100)) {
                        reject('请求二维结果 失败！！！')
                        return false
                    }

                    var worker = new Worker('/worker/meshOut.js')
                    worker.postMessage({
                        planID: this.planID,
                        resCell: resCell.data,
                        resPoint,
                        resMesh,
                        timesNodes,
                        hDiff: 0
                    })
                    this.loadingTxtStep = '构建淹没数据中，请稍后...|80%'
                    worker.onmessage = res => {
                        this.loadingTxtStep = '数据以就绪，请稍后...|100%'
                        var timeList = []
                        res.data.forEach(item => {
                            timeList.push(item.time.slice(0, -4))
                        })
                        this.$iDB.setItem(this.planID + '_meshOut', res.data)
                        this.$iDB.setItem(this.planID + '_timeList', timeList)
                        this.resArrMeshOut = res.data
                        resolve(timeList)
                        this.loadingTxtStep = ''
                    }
                }, e => {
                    this.resArrMeshOut = []
                    resolve([])
                    this.loadingTxtStep = ''
                })
            })
        },
        playOutMesh(row) {
            var geometryInstances = []
            if (isNaN(row[0].st[0])) {
                console.log('没有坐标')
                this.$store.dispatch('playerClose')
                this.reLoadData()
            }
            row.forEach(item => {
                var positions = new Float64Array(item.cartesian3s)
                const geo = new Cesium.Geometry({
                    attributes: {
                        position: new Cesium.GeometryAttribute({
                            componentDatatype: Cesium.ComponentDatatype.DOUBLE,
                            componentsPerAttribute: 3,
                            values: positions
                        }),
                        st: new Cesium.GeometryAttribute({
                            componentDatatype: Cesium.ComponentDatatype.FLOAT,
                            componentsPerAttribute: 2,
                            values: new Float32Array(item.st),
                            normalize: false
                        })
                    },
                    // 索引
                    indices: new Uint16Array([0, 1, 2, 2, 3, 0]),
                    // 绘制类型
                    primitiveType: Cesium.PrimitiveType.TRIANGLES,
                    boundingSphere: Cesium.BoundingSphere.fromVertices(positions)
                })
                var g = Math.round(127 + Math.round(item.x * 10))
                var b = Math.round(127 + Math.round(item.y * 10))
                var color = `rgba(0,${g},${b},255)`
                if (this.addHeat) {
                    // 将1-60的颜色级别转成R通道 0-240的色彩范围进行传值转换
                    color = `rgba(${item.colorIndex * 4},${g},${b},255)`
                }
                var geoColor
                if (this.addAlpha) {
                    var a = (item.colorIndex / 60) * 0.7 + 0.3
                    geoColor = Cesium.Color.fromCssColorString(color).withAlpha(a)
                } else {
                    geoColor = Cesium.Color.fromCssColorString(color)
                }
                var instance = new Cesium.GeometryInstance({
                    geometry: geo,
                    attributes: {
                        // color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromCssColorString('#cc2300'))
                        color: Cesium.ColorGeometryInstanceAttribute.fromColor(geoColor)
                        // show : new Cesium.ShowGeometryInstanceAttribute(false)
                    },
                    id: {
                        name: row.time + '_' + item.meshCode,
                        eventName: 'WaterMesh',
                        prop: {
                            sw: item.sw,
                            deep: item.deep,
                            a: item.a,
                            x: item.x,
                            y: item.y,
                            meshCode: item.meshCode
                        }
                    }
                })
                geometryInstances.push(instance)
            })
            var primitive = new Cesium.Primitive({
                geometryInstances: geometryInstances,
                appearance: this.appearance,
                asynchronous: false,
                show: true
            })
            this.clearOutWaterMesh()
            this.lastOutPrimitives = this.$viewer.scene.primitives.add(primitive)
        },
        playInMesh(row) {
            if (isNaN(row[0].st[0])) {
                console.log('没有坐标')
            }
            var geometryInstances = []
            row.forEach(item => {
                var indices = [0, 1, 2]
                if (item.cartesian3s.length === 12) {
                    indices = [0, 1, 2, 2, 3, 0]
                }
                // console.log(item.cartesian3s.length, item.st.length)
                var positions = new Float64Array(item.cartesian3s)
                const geo = new Cesium.Geometry({
                    attributes: {
                        position: new Cesium.GeometryAttribute({
                            componentDatatype: Cesium.ComponentDatatype.DOUBLE,
                            componentsPerAttribute: 3,
                            values: positions
                        }),
                        st: new Cesium.GeometryAttribute({
                            componentDatatype: Cesium.ComponentDatatype.FLOAT,
                            componentsPerAttribute: 2,
                            values: new Float32Array(item.st),
                            normalize: false
                        })
                    },
                    // 索引
                    indices: new Uint16Array(indices),
                    // 绘制类型
                    primitiveType: Cesium.PrimitiveType.TRIANGLES,
                    boundingSphere: Cesium.BoundingSphere.fromVertices(positions)
                })
                var color = '#3d6f7b'
                var instance = new Cesium.GeometryInstance({
                    geometry: geo,
                    attributes: {
                        color: Cesium.ColorGeometryInstanceAttribute.fromColor(
                            Cesium.Color.fromCssColorString(color)
                        )
                        // show : new Cesium.ShowGeometryInstanceAttribute(false)
                    }
                })
                geometryInstances.push(instance)
            })
            var primitive = new Cesium.Primitive({
                geometryInstances: geometryInstances,
                appearance: this.appearanceIn,
                // appearance: new Cesium.PerInstanceColorAppearance({
                //     flat: true,
                //     translucent: false
                // }),
                asynchronous: false,
                show: true
            })
            this.clearInWaterMesh()
            this.lastInPrimitives = this.$viewer.scene.primitives.add(primitive)
        },

        playWaterMesh(index) {
            if (this.resArrMeshOut && this.resArrMeshIn) {
                this.playOutMesh(this.resArrMeshOut[index].meshs)
                this.playInMesh(this.resArrMeshIn[index].meshs)
            }
        },
        reLoadData() {
            this.getAllDatas(true, true).then(timeList => {
                // console.log(timeList)
                this.timeList = timeList
                var player = this.$store.getters.playerParams
                player.name = 'PlanYMGC'
                player.dragReal = false
                player.width = '50%'
                player.show = true
                player.currIndex = 0
                player.times = timeList
                this.$store.dispatch('playerParams', player)
                this.playWaterMesh(0)
            })
        },
        clearMemory() {
            this.resArrMeshOut = []
            this.resArrMeshIn = []
        },
        clearOutWaterMesh() {
            if (this.lastOutPrimitives) {
                this.$viewer.scene.primitives.remove(this.lastOutPrimitives)
                this.lastOutPrimitives = null
            }
        },
        clearInWaterMesh() {
            if (this.lastInPrimitives) {
                this.$viewer.scene.primitives.remove(this.lastInPrimitives)
                this.lastInPrimitives = null
            }
        },
        initWaterMeshEvent() {
            var eventFn = (pickedObject, position) => {
                if (
                    pickedObject &&
                    pickedObject.id &&
                    pickedObject.id.eventName
                ) {
                    if (pickedObject.id.eventName === 'WaterMesh') {
                        const popParams = this.$store.getters.popParams
                        popParams.name = '通用'
                        popParams.show = true
                        popParams.posX = Math.round(position.x)
                        popParams.posY = Math.round(position.y)
                        popParams.remarks = [{ name: '网格编号', value: pickedObject.id.prop.meshCode },
                            { name: '水位', value: pickedObject.id.prop.sw },
                            { name: '水深', value: pickedObject.id.prop.deep },
                            // { name: 'a', value: pickedObject.id.prop.a },
                            { name: 'X流速', value: pickedObject.id.prop.x },
                            { name: 'Y流速', value: pickedObject.id.prop.y }
                        ]
                        this.$store.dispatch('popParams', popParams)
                    }
                }
            }
            this.$store.getters.eventCesiumOption.leftPickFns.set('WaterMesh', eventFn)
        }
    }
}
